package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.utils.BCryptPasswordEncoderUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;
    @Resource
    private RoleDao roleDao;
    @Resource
    private PermissionDao permissionDao;
    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        if (user==null){
            return null;
        }

        Set<Role> roles = roleDao.findRolesByUserId(user.getId());
        if (roles!=null&&roles.size()>0){
            for (Role role : roles) {
                Set<Permission> permissions = permissionDao.findPermissionByRoleId(role.getId());
                if (permissions!=null&&permissions.size()>0){
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }
        return user;
    }

    @Override
    public void add(User user, Integer[] roleIds) {
        user.setPassword(BCryptPasswordEncoderUtils.encodePassword(user.getPassword()));
        userDao.add(user);

        setUserAndRole(user,roleIds);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<User> page = userDao.findPage(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void delete(String id) {
        //根据检查组id查询是否有关联的检查项
        List<Integer> list = userDao.findRoleIdsByuserId(id);
        if (list.size()>0){
            throw new RuntimeException("当前用户被引用，不能删除");
        }
        userDao.delete(id);
    }

    @Override
    public User findById(String id) {
        return userDao.findById(id);
    }

    @Override
    public List<Integer> findRoleIdsByUserId(String id) {
        return userDao.findRoleIdsByuserId(id);
    }

    @Override
    public void edit(User user, Integer[] roleIds) {
        user.setPassword(BCryptPasswordEncoderUtils.encodePassword(user.getPassword()));
        //更新基本信息
        userDao.edit(user);
        //根据检查组id删除中间表数据（清理原有关联关系）
        userDao.deleteAssociation(user.getId());
        //将修改后的关系设置上去
        setUserAndRole(user,roleIds);
    }

    private void setUserAndRole(User user, Integer[] roleIds) {
        Integer userId = user.getId();

        if (roleIds!=null&&roleIds.length>0){
            for (Integer roleId : roleIds) {
                userDao.setUserAndRole(userId,roleId);
            }
        }
    }
}
